<?php
/**
 * Created by jinqiang on 2025/4/9 13:48.
 * Copyright (c) 2025, Your Company. All rights reserved.
 */


namespace App\Http\Repository;



use App\Http\Models\Mysql\SsyProcessingListTable;
use App\Http\Models\Mysql\SsyPushLmLogTable;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;

class LinmaoRepository
{
    private $_appId = "5a38bbad-3991-431d-8989-d4ae4889d3e6";

    private $_appSecret = "faaf996a-4e47-49fa-a4b8-53d3314a0376";

    private $_token;

    private $_host = "https://open.scm321.com";

    private function getToken()
    {
        $cacheKey = "LINMAO_TOKEN";
        $this->_token = Cache::get($cacheKey);
        if(empty($this->_token)){
            $form = [
                'headers' => ["Content-type:application/json; charset=utf-8","Accept:application/json"],
                'json' => json_encode(['AppId' => $this->_appId, 'AppSecret' => $this->_appSecret])
            ];
            $resp = httpCurl($this->_host."/auth/token", $form);
            $resp = json_decode($resp, true);
            if(isset($resp['data']['token'])){
                Cache::put($cacheKey, $resp['data']['token'], Carbon::now()->addMinutes(110));
                $this->_token = $resp['data']['token'];
            }
        }
    }

    //款式信息接口
    public function getProduct($param)
    {
        list($page, $size, $codes, $modifiedBegin, $modifiedEnd) = [$param['page'], $param['size'], $param['codes'] ?? "", $param['modifiedBegin'], $param['modifiedEnd']];
        $this->getToken();
        $json = ['pageIndex' => $page, 'pageSize' => $size];
        if(!empty($codes)){
            $json['codes'] = $codes;
        }else{
            $json['modifiedBegin'] = $modifiedBegin;
            $json['modifiedEnd'] = $modifiedEnd;
        }
        $form = [
            'headers' => ["Content-type:application/json; charset=utf-8","Accept:application/json", "Authorization:Bearer ".$this->_token],
            'json' => json_encode($json)
        ];
        $resp = httpCurl($this->_host."/v1/product/getproducts", $form);
        return json_decode($resp, true);
    }

    //物料清单接口
    public function getProductMaterial($param)
    {
        list($page, $size, $codes, $modifiedBegin, $modifiedEnd) = [
            $param['page'], $param['size'], $param['codes'] ?? "", $param['modifiedBegin'] ?? 1, $param['modifiedEnd'] ?? 100
        ];
        $this->getToken();
        $json = ['pageIndex' => $page, 'pageSize' => $size];
        if(!empty($codes)){
            $json['pdtCodes'] = $codes;
        }else{
            $json['modifiedBegin'] = $modifiedBegin;
            $json['modifiedEnd'] = $modifiedEnd;
        }
        $form = [
            'headers' => ["Content-type:application/json; charset=utf-8","Accept:application/json", "Authorization:Bearer ".$this->_token],
            'json' => json_encode($json)
        ];
        $resp = httpCurl($this->_host."/v1/product/standardbom/getmaterials", $form);
        return json_decode($resp, true);
    }

    //工艺指示接口
    public function getProductGy($param)
    {
        list($page, $size, $codes, $modifiedBegin, $modifiedEnd) = [
            $param['page'], $param['size'], $param['codes'] ?? "", $param['modifiedBegin'] ?? 1, $param['modifiedEnd'] ?? 100
        ];
        $this->getToken();
        $json = ['pageIndex' => $page, 'pageSize' => $size];
        if(!empty($codes)){
            $json['pdtCodes'] = $codes;
        }else{
            $json['modifiedBegin'] = $modifiedBegin;
            $json['modifiedEnd'] = $modifiedEnd;
        }
        $form = [
            'headers' => ["Content-type:application/json; charset=utf-8","Accept:application/json", "Authorization:Bearer ".$this->_token],
            'json' => json_encode($json)
        ];
        $resp = httpCurl($this->_host."/v1/product/standardbom/getprocguides", $form);
        return json_decode($resp, true);
    }

    //核价清单接口
    public function getProductPrice($param)
    {
        list($page, $size, $pdtCodes, $modifiedBegin, $modifiedEnd) = [
            $param['page'], $param['size'], $param['codes'] ?? "", $param['modifiedBegin'] ?? 1, $param['modifiedEnd'] ?? 100
        ];
        $this->getToken();
        $json = ['pageIndex' => $page, 'pageSize' => $size];
        if(!empty($pdtCodes)){
            $json['pdtCodes'] = $pdtCodes;
        }else{
            $json['modifiedBegin'] = $modifiedBegin;
            $json['modifiedEnd'] = $modifiedEnd;
        }
        $form = [
            'headers' => ["Content-type:application/json; charset=utf-8","Accept:application/json", "Authorization:Bearer ".$this->_token],
            'json' => json_encode($json)
        ];
        $resp = httpCurl($this->_host."/v1/product/standardbom/getpkgfees", $form);
        return json_decode($resp, true);
    }

    //物料信息接口
    public function getMaterial($param)
    {
        list($page, $size, $modifiedBegin, $modifiedEnd) = [$param['page'], $param['size'], $param['modifiedBegin'], $param['modifiedEnd']];
        $this->getToken();
        $json = ['pageIndex' => $page, 'pageSize' => $size];
        if(!empty($codes)){
            $json['codes'] = $codes;
        }else{
            $json['modifiedBegin'] = $modifiedBegin;
            $json['modifiedEnd'] = $modifiedEnd;
        }
        $form = [
            'headers' => ["Content-type:application/json; charset=utf-8","Accept:application/json", "Authorization:Bearer ".$this->_token],
            'json' => json_encode($json)
        ];
        $resp = httpCurl($this->_host."/v1/BaseInfo/Getmaterials", $form);
        return json_decode($resp, true);
    }

    //供应商信息接口
    public function getSupplier($param)
    {
        list($page, $size, $modifiedBegin, $modifiedEnd, $codes) = [$param['page'], $param['size'], $param['modifiedBegin'] ?? "", $param['modifiedEnd'] ?? "",
            $param['codes']];
        $this->getToken();
        $json = ['pageIndex' => $page, 'pageSize' => $size];
        if(!empty($codes)){
            $json['codes'] = $codes;
        }else{
            $json['modifiedBegin'] = $modifiedBegin;
            $json['modifiedEnd'] = $modifiedEnd;
        }
        $form = [
            'headers' => ["Content-type:application/json; charset=utf-8","Accept:application/json", "Authorization:Bearer ".$this->_token],
            'json' => json_encode($json)
        ];
        $resp = httpCurl($this->_host."/v1/BaseInfo/getsuppliers", $form);
        return json_decode($resp, true);
    }

    //成品采购单查询
    public function getbills($param)
    {
        list($page, $size, $codes, $modifiedBegin, $modifiedEnd, $productionType) = [
            $param['page'], $param['size'], $param['codes'], $param['modifiedBegin'], $param['modifiedEnd'], $param['productionType'] ?? 0
        ];
        $this->getToken();
        $json = ['pageIndex' => $page, 'pageSize' => $size, 'productionType' => $productionType];
        if(!empty($codes)){
            $json['codes'] = $codes;
        }else{
            $json['modifiedBegin'] = $modifiedBegin;
            $json['modifiedEnd'] = $modifiedEnd;
        }
        $form = [
            'headers' => ["Content-type:application/json; charset=utf-8","Accept:application/json", "Authorization:Bearer ".$this->_token],
            'json' => json_encode($json)
        ];
        $resp = httpCurl($this->_host."/v1/pdtpurchase/getbills", $form);
        return json_decode($resp, true);
    }

    //新增修改成品入库单
    public function pushOrder($param)
    {
        $processingCode = $param['processing_code'];
        $processingObj = (new SsyProcessingListTable())->where('processing_code', $processingCode)->where('sku_code', $param['sku_id'])
            ->first(['unit_price', 'source_type', 'ly_processing_code']);
        //增裁单原始单据溯源
        if(!empty($processingObj) && $processingObj->source_type == 5){
            $processingCode = $processingObj->ly_processing_code;
        }
        $linkType = substr($processingCode, 0, 2);
        $data = [
            "billType" => "18",
            "spCode" => $param['supplier_id'],
            "store" => $param['warehouse'],
            "billDate" => $param['io_date'],
            "statuz" => 1,
            "CheckMan" => "NNYY_SCM",
            "CheckDate" => date('Y-m-d H:i:s'),
            "sysType" => "NNYY_SCM",
            "operator" => "NNYY_SCM",
            "linkCode" => $processingCode,
            "linkType" => $linkType == "PO" ? "CG" : ($linkType == "MO" ? "WF" : "QT"),
            "apiCode" => $param['po_id']."_".$param['id'],
            "subs" =>[
                [
                    "skuCode" => $param['sku_id'],
                    "qty" => $param['qty'],
                    "price" => $processingObj->unit_price ?? 0
                ]
            ]
        ];
        $this->getToken();
        $form = [
            'headers' => ["Content-type:application/json; charset=utf-8","Accept:application/json", "Authorization:Bearer ".$this->_token],
            'json' => json_encode($data)
        ];
        $resp = httpCurl($this->_host."/v1/pdtstorage/updateinbill", $form);
        $res = json_decode($resp, true);
        //记录推送日志
        $pushLog = [
            "purchasein_id" => $param['id'],
            "data" => json_encode($data, JSON_UNESCAPED_UNICODE),
            "error" => json_encode($res, JSON_UNESCAPED_UNICODE),
            "create_time" => date('Y-m-d H:i:s'),
            "update_time" => date('Y-m-d H:i:s')
        ];
        if($res['code'] == 200 && $res['isSuccess']){
            $pushLog['status'] = 1;
        }else{
            $pushLog['status'] = 0;
        }
        $logExist = (new SsyPushLmLogTable())->where('purchasein_id', $param['id'])->first();
        if(!empty($logExist)){
            (new SsyPushLmLogTable())->updateData($logExist->id, $pushLog);
        }else{
            (new SsyPushLmLogTable())->createData($pushLog);
        }
        return [
            'code' => $pushLog['status'] == 1 ? 0 : -1,
            'msg' => $pushLog['status'] == 1 ? "推送成功" : "推送失败",
            'data' => $resp
        ];
    }
}
